package edu.biwu.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author 王俊彪
 * @version 1.0
 */
@Component
public class TransactionManager {

    @Autowired
    ConnectionFactory connectionFactory;

    @Autowired
    ThreadLocal<Connection> threadLocal;

    /**
     * 开启事务
     */
    public void beginTransaction(){
        try {
            connectionFactory.currentThreadConn().setAutoCommit(false);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 提交事务
     */
    public void commit(){
        try {
            connectionFactory.currentThreadConn().commit();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 回滚事务
     */
    public void rollBack(){
        try {
            connectionFactory.currentThreadConn().rollback();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 释放资源
     */
    public void release(){
        try {
            connectionFactory.currentThreadConn().close();
            threadLocal.remove();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
